

# Use control history (with modified parameters).



import matplotlib.pyplot as plt
import numpy as np
import csv
import pid_simples
import sys
import math
import random
import seaborn as sns


from models import *

import embetant



# Mostre  gráfico de saída.
flag_grafico       = True

# Controle (que é lido de arquivo) interfere no modelo.
flag_ctrl          = True

# Dados não são gerados.
flag_generate_data = False

# Nomad não está funcionando.
flag_running_nomad = False


Gpid = pid_simples.PID (0.0 , 0.0 , 0.0)


if flag_ctrl:
    Gpid.coeficientes ( 0.0 , 0.0 , 0.0)
    flag_generate_data = False



Gerro    = 0.0
Gidxctrl = 0
embetant.Ghistoryctrl  = []



#----------------------------------------------------
def mul (num,v):
   return [valor * num for valor in v]

#----------------------------------------------------
def add (v1,v2):
   n = len(v1)
   v = []
   for k in range(n):
      v.append (v1[k] + v2[k])
   return v

#----------------------------------------------------
def RK (f, t, dt, s, alpha = 0.8, beta = 0.1, gamma = 0.4, delta = 0.1) :

#   t = 0
   one6 = 1./6.
   one3 = 1./3.
   h = dt
   t0 = t
   half    = h * 0.5
   t_h     = t0 + h
   t_half  = t0 + half

   v1 = mul (h , f (t0, s, a = alpha, b=beta, c = gamma, d=delta))
   vt = add (v1, mul (0.5, v1))

   v2 = mul (h , f (t_half, vt, a = alpha, b=beta, c = gamma, d=delta))
   vt = add (v2, mul (0.5, v1))

   v3 = mul (h , f (t_half, vt, a = alpha, b=beta, c = gamma, d=delta))
   vt = add (s, v3)

   v4 = mul (h , f (t_h   , vt, a = alpha, b=beta, c = gamma, d=delta))

#   vt = add (s, add( \
#         mul (one6, v1), add( \
#         mul (one3, v2), add( \
#         mul (one3, v3), \
#         mul (one6, v4)))))

   vt = add (s, \
          add( mul (one6, v1), \
            add( mul (one3, v2), \
              add (mul (one3, v3), mul (one6, v4)))))

   return vt





#====================================================================



#Ler trajetória de referência -------------------------------------------
try:
    arq  = open('Reference.csv', 'r')

    line = arq.readline()
    Rx = [float (x) for x in line.split(',')]

    line = arq.readline()
    Ry = [float (y) for y in line.split(',')]


except:
    print ("Impossível ler Trajetória de Referência, Reference.csv!")
    sys.exit (-1)




try:
    arq  = open('Ctrl.csv', 'r')
    line = arq.readline()
    embetant.Ghistoryctrl = [float (x) for x in line.split(',')]

except:
    print ("Impossível ler Ctrl.csv!")
    sys.exit (-1)



dt = 1.0 / 256.0


# Playing with parameters.

alpha = 0.8 * 1.05
beta  = 0.1 
gamma = 0.4 * 0.95
delta = 0.1 
stitle = r'$\alpha = .84 , \gamma = 0.38$'


alpha = 0.8 * 0.95
beta  = 0.1 
gamma = 0.4 * 1.05
delta = 0.1 
stitle = r'$\alpha = .76 , \gamma = 0.42$'




#-------------- Lotka-Volterra original ----------------
s   = [10., 10.]
Lx = [10.0]
Ly = [10.0]
for t in range(10000):
    o = RK (LotkaVolterra, t, dt, s, alpha, beta, gamma, delta)
    Lx.append(o[0])
    Ly.append(o[1])
    s = o


#-------------- Lotka-Volterra modificado  ----------------
s   = [10., 10.]
Mx = [10.0]
My = [10.0]
for t in range(10000):
    o = RK (LotkaVolterraModif, t, dt, s, alpha, beta, gamma, delta)
    Mx.append(o[0])
    My.append(o[1])
    s = o


#-------------- Controle PID beta = 0.012 ----------------
s   = [10., 10.]
Cx = [10.0]
Cy = [10.0]
for t in range(10000):
    o = RK (LotkaVolterraPID, t, dt, s, alpha, beta, gamma, delta)
    Cx.append(o[0])
    Cy.append(o[1])
    s = o



plt.title (stitle, fontsize=18)
#plt.plot(Cy, lw=1.0, color='green' , linestyle = (0, (5, 10)), label='Simulation')
plt.plot(Ry, lw=1.0, color='blue'  , linestyle = 'dashed', label='Reference')
plt.plot(Cy, lw=1.0, color='green' ,                       label='Simulation')
plt.plot(Ly, lw=1.5, color='black' , linestyle = 'dotted', label='Base model')

plt.grid ()

plt.subplots_adjust(
top=0.88,
bottom=0.13,
left=0.125,
right=0.9,
hspace=0.2,
wspace=0.2
)


plt.legend()


plt.xlabel ('Time', fontsize=16)
plt.ylabel ('Predators', fontsize=16)

ax = plt.gca()

sns.move_legend(ax, "upper right")


for item in (\
             #[ax.title,ax.xaxis.label, ax.yaxis.label] + \
             ax.get_xticklabels() + ax.get_yticklabels()):
    item.set_fontsize(14)

for item in ax.get_legend().get_texts():
    item.set_fontsize(12)

plt.draw ()

#plt.savefig('Figure-6b.eps', format='eps')
#plt.savefig('Figure-6b.png', dpi=400)

plt.show()



